import React, { useEffect, useRef, useState } from 'react';
import { Row, Col, Icon, Select, InputNumber, Form, Typography } from 'antd';
import { size } from 'lodash';
import { getLeaveTypeList } from '@/pages/WorkFlow/components/FormControls/components/AutoRenderComponent/components/LeaveType/service';
import { getGradeList } from '@/services/organization';
import { dictionaryList } from '@/services/dictionary';
import OrgListSelect from '../OrgListSelect';
import styles from '../styles.less';

const { Option } = Select;
const { Paragraph } = Typography;

// 表达式集合
const CONDS = [
    {
        value: 'EQ',
        label: '等于'
    },
    {
        value: 'GT',
        label: '大于'
    },
    {
        value: 'GTE',
        label: '大于等于'
    },
    {
        value: 'LT',
        label: '小于'
    },
    {
        value: 'LTE',
        label: '小于等于'
    },
    {
        value: 'NOT',
        label: '不等于'
    }
];

// 条件节点条件表单
const RenderConditionForm = ({
    data = [],
    onDelete,
    showingPCons = [],
    form,
    conditionData = [],
    setConditionData,
    organizationCode
}) => {
    const orgRef = useRef(null);

    const [leaveTypeList, setLeaveTypeList] = useState([]);
    const [leaveTypeLoading, setLeaveTypeLoading] = useState(false);
    // 获取请假类型
    const fetchLeaveTypeList = async () => {
        setLeaveTypeLoading(true);
        const { code, data: sdata } = await getLeaveTypeList();

        if (code === 10000 && sdata) {
            setLeaveTypeList(sdata);
        } else {
            setLeaveTypeList(null);
        }
        setLeaveTypeLoading(false);
    };

    const [gradeList, setGradeList] = useState([]);
    const [gradeLoading, setGradeLoading] = useState(false);
    // 获取职级列表
    const fetchGradeList = async () => {
        setGradeLoading(true);
        const { code, data: sdata } = await getGradeList({ organizationCode });
        if (code === 10000 && sdata) {
            setGradeList(sdata);
        } else {
            setGradeList(null);
        }
        setGradeLoading(false);
    };

    const [dictList, setDictList] = useState([]);
    const [dictLoading, setDictLoading] = useState(false);
    // 获取字典信息
    const fetchDictList = async params => {
        setDictLoading(true);
        const { code, data: sdata } = await dictionaryList(params);
        if (code === 10000 && sdata) {
            setDictList(sdata);
        } else {
            setDictList(null);
        }
        setDictLoading(false);
    };

    useEffect(() => {
        // 发起人
        const tempArr = [];
        const initatorObj = form.getFieldValue('initator');
        if (size(initatorObj) > 0) {
            const obj = {
                formId: 'initiatorCondition',
                tag: 'initator', // 类型
                conditionValuesType: 'OR',
                conditionValues: [],
                labelText: '',
                backData: initatorObj
            };
            Object.keys(initatorObj).forEach(item => {
                let tempValue = initatorObj[item].value;
                if (!tempValue) return;
                const tempLabel = [];
                if (!Array.isArray(tempValue)) {
                    tempValue = [tempValue];
                }
                if (size(tempValue) > 0) {
                    tempValue.forEach(subItem => {
                        tempLabel.push(subItem.label);
                        obj.conditionValues.push({
                            key: initatorObj[item].keyVariable,
                            value: subItem.value ? subItem.value : subItem.key,
                            cond: 'EQ'
                        });
                    });

                    obj.labelText += `\n<b>${initatorObj[item].typeText}</b>：${tempLabel.join('，')}；`;
                }
            });
            if (obj.conditionValues.length > 0) {
                obj.labelText = `【发起人属于： ${obj.labelText}】`;
                tempArr.push(obj);
            }
        }

        // 其他条件
        data.filter(x => showingPCons.includes(x.formId)).forEach(item => {
            const { showType } = item?.conditionShowOption || {};

            const obj = {
                formId: item.formId,
                conditionValuesType: 'AND',
                conditionValues: []
            };
            switch (showType) {
                case 'number':
                    {
                        const cond = form.getFieldValue(`${item.formId}-cond`);
                        const num = form.getFieldValue(`${item.formId}-number`);
                        if (num && num !== '') {
                            // 数据回显用
                            obj.backData = {
                                [`${item.formId}-number`]: num,
                                [`${item.formId}-cond`]: cond
                            };
                            // 节点展示用
                            obj.labelText = `【${item.label}：${cond.label || cond[0].label} ${num}】\n`;
                            // 后端需要数据
                            obj.conditionValues.push({
                                key: item.formId,
                                value: num,
                                cond: cond.key || cond[0].key
                            });
                        }
                    }
                    break;
                case 'select':
                    {
                        const cond = form.getFieldValue(`${item.formId}-cond`);
                        let selt = form.getFieldValue(`${item.formId}`);
                        obj.conditionValuesType = cond.key || cond[0].key;
                        if (size(selt) > 0) {
                            let temp = `【 ${item.label}：${cond.label || cond[0].label}`;
                            if (!Array.isArray(selt)) {
                                selt = [selt];
                            }
                            selt.forEach(subItem => {
                                obj.backData = {
                                    [`${item.formId}-cond`]: cond,
                                    [`${item.formId}`]: selt
                                };
                                temp = `${temp} ${subItem.label}`;
                                obj.conditionValues.push({
                                    key: item.formId,
                                    value: subItem.key || subItem.value,
                                    cond: 'EQ'
                                });
                            });
                            temp = `${temp} 】\n`;
                            obj.labelText = temp;
                        }
                    }
                    break;
                default:
                    break;
            }
            if (obj.conditionValues.length > 0) {
                tempArr.push(obj);
            }
        });

        setConditionData([...tempArr]);
        console.log('===============================================>tempArr', tempArr);
    }, [JSON.stringify(form.getFieldsValue()), showingPCons]);

    // 获取默认值
    const getinitialValue = (id, key) => {
        const obj = conditionData.filter(x => x.formId === id);
        if (obj.length > 0) {
            if (id === 'initiatorCondition') {
                return obj[0].backData;
            }
            if (key) {
                return obj[0].backData[key];
            }
            return obj[0].backData[id];
        }
        return undefined;
    };

    // 渲染表单项
    const renderFormItem = item => {
        const { valueMode, showType, fetchType, query = {}, numberProps = {} } = item?.conditionShowOption || {};

        // 判断如果数据中包含指定类型，拉取相对的数据
        if (fetchType === 'grade' && gradeList && gradeList.length === 0 && gradeLoading === false) {
            fetchGradeList();
        }
        if (fetchType === 'leave' && leaveTypeList && leaveTypeList.length === 0 && leaveTypeLoading === false) {
            fetchLeaveTypeList();
        }
        if (fetchType === 'dict' && size(query) > 0 && dictList && dictList.length === 0 && dictLoading === false) {
            fetchDictList(query);
        }

        switch (showType) {
            case 'number':
                return (
                    <Row gutter={9}>
                        <Col span={12}>
                            <Form.Item>
                                {form.getFieldDecorator(`${item.formId}-cond`, {
                                    initialValue: getinitialValue(`${item.formId}`, `${item.formId}-cond`) || [
                                        { key: 'EQ', label: '等于' }
                                    ]
                                })(
                                    <Select labelInValue>
                                        {CONDS.map(subItem => (
                                            <Option value={subItem.value} key={subItem.label}>
                                                {subItem.label}
                                            </Option>
                                        ))}
                                    </Select>
                                )}
                            </Form.Item>
                        </Col>
                        <Col span={12}>
                            <Form.Item>
                                {form.getFieldDecorator(`${item.formId}-number`, {
                                    initialValue: getinitialValue(`${item.formId}`, `${item.formId}-number`)
                                })(<InputNumber style={{ width: '100%' }} {...numberProps} />)}
                            </Form.Item>
                        </Col>
                    </Row>
                );
            case 'select':
                return (
                    <Row gutter={9}>
                        <Col span={8}>
                            <Form.Item>
                                {form.getFieldDecorator(`${item.formId}-cond`, {
                                    initialValue: getinitialValue(`${item.formId}`, `${item.formId}-cond`) || [
                                        { key: 'OR', label: '属于' }
                                    ]
                                })(
                                    <Select labelInValue>
                                        <Option value="OR" key="属于">
                                            属于
                                        </Option>
                                    </Select>
                                )}
                            </Form.Item>
                        </Col>
                        <Col span={16}>
                            <Form.Item>
                                {form.getFieldDecorator(`${item.formId}`, {
                                    initialValue: getinitialValue(`${item.formId}`)
                                })(
                                    <Select
                                        mode={valueMode}
                                        allowClear
                                        placeholder="请选择"
                                        labelInValue
                                        disabled={false}
                                    >
                                        {fetchType === 'leave' &&
                                            leaveTypeList?.length > 0 &&
                                            leaveTypeList?.map(subItem => (
                                                <Option key={subItem.leaveName} value={subItem.leaveCode}>
                                                    {subItem.leaveName}
                                                </Option>
                                            ))}

                                        {fetchType === 'grade' &&
                                            gradeList?.length > 0 &&
                                            gradeList?.map(subItem => (
                                                <Option key={subItem.id} value={subItem.id}>
                                                    {subItem.gradeCode}
                                                </Option>
                                            ))}

                                        {fetchType === 'dict' &&
                                            dictList?.length > 0 &&
                                            dictList?.map(subItem => (
                                                <Option key={subItem.dictValue} value={subItem.dictValue}>
                                                    {subItem.dictName}
                                                </Option>
                                            ))}

                                        {(item.dataList || []).map(subItem => (
                                            <Option key={subItem.value} value={subItem.value}>
                                                {subItem.label}
                                            </Option>
                                        ))}
                                    </Select>
                                )}
                            </Form.Item>
                        </Col>
                    </Row>
                );

            default:
                return null;
        }
    };

    return (
        <div style={{ overflowX: 'hidden' }} className={styles.renderConditionFormWrap}>
            <Form labelAlign="left" labelCol={{ span: 5 }} wrapperCol={{ span: 18 }}>
                {showingPCons.includes('initiatorCondition') && (
                    <Form.Item key="initator" wrapperCol={{ span: 24 }}>
                        <Row gutter={16}>
                            <Col span={22} className={styles.paneTitle}>
                                发起人
                            </Col>
                            <Col span={2}>
                                <Icon
                                    type="delete"
                                    onClick={() => {
                                        if (onDelete) {
                                            onDelete('initiatorCondition');
                                        }
                                    }}
                                />
                            </Col>
                        </Row>
                        {form.getFieldDecorator('initator', {
                            initialValue: getinitialValue('initiatorCondition'),
                            valuePropName: 'defaultValue'
                        })(<OrgListSelect organizationCode={organizationCode} ref={orgRef} />)}
                    </Form.Item>
                )}
                {data &&
                    data.length > 0 &&
                    data.map(item => {
                        if (showingPCons.includes(item.formId)) {
                            return (
                                <Form.Item
                                    label={
                                        <Paragraph ellipsis title={item.label}>
                                            {item.label}
                                        </Paragraph>
                                    }
                                    colon={false}
                                    key={item.tag + item.formId}
                                >
                                    <Row gutter={16}>
                                        <Col span={22}>{renderFormItem(item)}</Col>
                                        <Col span={2}>
                                            <Icon
                                                type="delete"
                                                onClick={() => {
                                                    if (onDelete) {
                                                        onDelete(item.formId);
                                                    }
                                                }}
                                            />
                                        </Col>
                                    </Row>
                                </Form.Item>
                            );
                        }
                        return null;
                    })}
            </Form>
        </div>
    );
};

export default Form.create({ name: 'RenderConditionForm' })(RenderConditionForm);
